import React, { useEffect, useState } from 'react';
import { Form, Input, Select, Switch, InputNumber, Button, Space, Card, Typography, Divider, message, Collapse } from 'antd';
import { Model, ModelFormValues, ModelType, ConnectionType } from './store/modelTypes';
import { CaretRightOutlined } from '@ant-design/icons';

const { TextArea } = Input;
const { Title } = Typography;
const { Panel } = Collapse;

interface ModelFormProps {
  initialValues?: Model;
  defaultType?: 'chat' | 'embedding' | 'reRanking';
  type?: 'create' | 'edit' | 'view';
  onSubmit: (values: any) => Promise<void>;
  onCancel: () => void;
}

const ModelForm: React.FC<ModelFormProps> = ({ initialValues, defaultType, type, onSubmit, onCancel }) => {
  const [form] = Form.useForm();
  const [modelType, setModelType] = useState<string>(initialValues?.modelType || defaultType || 'chat');
  const [connectionType, setConnectionType] = useState<string>(initialValues?.connectionType || 'standard');
  const [isSystem, setIsSystem] = useState<boolean>(initialValues?.isSystem || false);
  const [activeAdvancedKeys, setActiveAdvancedKeys] = useState<string[]>([]);
  const [activeParamKeys, setActiveParamKeys] = useState<string[]>([]);

  useEffect(() => {
    form.resetFields();
    setModelType(initialValues?.modelType || defaultType || 'chat');
    setConnectionType(initialValues?.connectionType || 'standard');
    setIsSystem(initialValues?.isSystem || false);
  }, [initialValues, form]);

  const onFinish = async (values: any) => {
    try {
      await onSubmit(values);
      form.resetFields();
    } catch (error) {
      message.error('保存失败');
    }
  };

  const handleModelTypeChange = (value: string) => {
    setModelType(value);
    // 根据模型类型重置相关字段
    form.setFieldsValue({
      chatType: undefined,
      provider: undefined,
      dimension: undefined
    });
  };

  const handleConnectionTypeChange = (value: string) => {
    setConnectionType(value);
  };

  // 获取对应模型类型的选项
  const getChatTypeOptions = () => {
    switch (modelType) {
      case 'chat':
        return [
          { value: 'openai_gpt', label: 'GPT' },
          { value: 'claude', label: 'Claude' },
          { value: 'qwen', label: 'Qwen' },
          { value: 'wenxinyiyan', label: '文心一言' },
          { value: 'xinghuo', label: '星火' },
          { value: 'deepseek', label: 'Deepseek' },
          { value: 'doubao', label: '字节跳动' },
          { value: 'ollama', label: 'ollama' },
          { value: 'llm', label: 'vllm' },
          { value: 'custom', label: '自定义' }
        ];
      case 'embedding':
        return [
          { value: 'Embedding-V1', label: '百度向量模型' },
          { value: 'custom', label: '自定义向量模型' }
        ];
      case 'reRanking':
        return [
          { value: 'bce-reranker-base_v1', label: '百度重排序模型' },
          { value: 'custom', label: '自定义重排序模型' }
        ];
      default:
        return [];
    }
  };

  const isViewMode = type === 'view';
  const isSystemModel = isSystem;

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={onFinish}
      disabled={isViewMode}
      initialValues={{
        ...initialValues,
        modelType: defaultType || initialValues?.modelType,
      }}
    >
      {/* 基本信息卡片 */}
      <Card title="基本信息" style={{ marginBottom: 16 }}>
        <Form.Item
          name="mark"
          label="模型唯一标识"
          rules={[{ required: true, message: '请输入模型唯一标识' }]}
        >
          <Input placeholder="请输入模型唯一标识（英文、数字、下划线）" disabled={isSystemModel} />
        </Form.Item>

        <Form.Item
          name="name"
          label="模型名称"
          rules={[{ required: true, message: '请输入模型名称' }]}
        >
          <Input placeholder="请输入模型名称" />
        </Form.Item>

        <Form.Item
          name="modelType"
          label="模型分类"
          rules={[{ required: true, message: '请选择模型分类' }]}
        >
          <Select 
            placeholder="请选择模型分类" 
            onChange={handleModelTypeChange}
            disabled={isSystemModel}
          >
            <Select.Option value="chat">大语言模型</Select.Option>
            <Select.Option value="embedding">向量模型</Select.Option>
            <Select.Option value="reRanking">重排序模型</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="connectionType"
          label="对接方式"
          rules={[{ required: true, message: '请选择对接方式' }]}
        >
          <Select 
            placeholder="请选择对接方式" 
            onChange={handleConnectionTypeChange}
            disabled={isSystemModel}
          >
            <Select.Option value="standard">标准</Select.Option>
            <Select.Option value="custom">自定义</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="provider"
          label="提供商"
          rules={[{ required: true, message: '请选择提供商' }]}
        >
          <Select placeholder="请选择提供商" disabled={isSystemModel}>
            <Select.Option value="0">星枢</Select.Option>
            <Select.Option value="1">openAI</Select.Option>
            <Select.Option value="2">Anthropic</Select.Option>
            <Select.Option value="3">阿里</Select.Option>
            <Select.Option value="4">百度</Select.Option>
            <Select.Option value="5">讯飞</Select.Option>
            <Select.Option value="6">字节跳动</Select.Option>
            <Select.Option value="7">deepseek</Select.Option>
            <Select.Option value="999">自定义</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="chatType"
          label="模型类型"
          rules={[{ required: true, message: '请选择模型类型' }]}
        >
          <Select placeholder="请选择模型类型" disabled={isSystemModel}>
            {getChatTypeOptions().map(option => (
              <Select.Option key={option.value} value={option.value}>
                {option.label}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        {modelType === 'embedding' && (
          <Form.Item
            name="dimension"
            label="向量维度"
            rules={[{ required: true, message: '请输入向量维度' }]}
          >
            <InputNumber min={1} style={{ width: '100%' }} disabled={isSystemModel} />
          </Form.Item>
        )}

        <Form.Item
          name="status"
          label="模型状态"
          rules={[{ required: true, message: '请选择模型状态' }]}
        >
          <Select placeholder="请选择模型状态">
            <Select.Option value="active">活跃</Select.Option>
            <Select.Option value="inactive">未激活</Select.Option>
            <Select.Option value="deprecated">已弃用</Select.Option>
            <Select.Option value="maintenance">维护中</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="isSystem"
          label="是否系统自带"
          valuePropName="checked"
        >
          <Switch disabled={!!initialValues?.id} />
        </Form.Item>
      </Card>

      {/* 认证信息卡片 */}
      <Card title="认证信息" style={{ marginBottom: 16 }}>
        <Form.Item
          name="apiUrl"
          label="API地址"
          rules={[
            { required: connectionType === 'custom', message: '请输入API地址' },
            { type: 'url', message: '请输入有效的URL地址' }
          ]}
        >
          <Input placeholder="请输入API地址" disabled={isSystemModel && connectionType === 'standard'} />
        </Form.Item>

        <Form.Item
          name="apiKey"
          label="API密钥"
          rules={[
            { required: true, message: '请输入API密钥' },
            { min: 8, message: 'API密钥长度不能少于8个字符' }
          ]}
        >
          <Input.Password placeholder="请输入API密钥" />
        </Form.Item>

        <Form.Item
          name="apiSecret"
          label="API密钥（可选）"
          rules={[{ min: 8, message: 'API密钥长度不能少于8个字符' }]}
        >
          <Input.Password placeholder="请输入API密钥（部分模型需要）" />
        </Form.Item>

        {connectionType === 'custom' && (
          <Form.Item
            name="modelId"
            label="模型标识"
            rules={[{ required: true, message: '请输入模型标识' }]}
          >
            <Input placeholder="请输入模型提供方给到的模型标识" />
          </Form.Item>
        )}

        <Form.Item
          name="proxy"
          label="代理地址"
          rules={[{ type: 'url', message: '请输入有效的URL地址' }]}
        >
          <Input placeholder="请输入代理地址" />
        </Form.Item>
      </Card>

      {/* 参数设置卡片 - 仅对大语言模型显示，使用 Collapse 实现折叠 */}
      {modelType === 'chat' && (
        <Collapse
          activeKey={activeParamKeys}
          onChange={setActiveParamKeys}
          expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
          style={{ marginBottom: 16 }}
        >
          <Panel header="参数设置" key="params">
            <Form.Item
              name="maxTokens"
              label="最大token数"
              rules={[{ type: 'number', min: 1, message: '最大token数必须大于0' }]}
            >
              <InputNumber min={1} style={{ width: '100%' }}  placeholder="最大token数必须大于0" />
            </Form.Item>

            <Form.Item
              name="temperature"
              label="温度参数"
              rules={[{ type: 'number', min: 0, max: 2, message: '温度参数必须在0到2之间' }]}
            >
              <InputNumber min={0} max={2} step={0.1} style={{ width: '100%' }} placeholder="温度参数必须在0到2之间" />
            </Form.Item>

            <Form.Item
              name="topP"
              label="top_p参数"
              rules={[{ type: 'number', min: 0, max: 1, message: 'top_p参数必须在0到1之间' }]}
            >
              <InputNumber min={0} max={1} step={0.1} style={{ width: '100%' }} placeholder="top_p参数必须在0到1之间" />
            </Form.Item>

            <Form.Item
              name="frequencyPenalty"
              label="频率惩罚"
              rules={[{ type: 'number', min: -2, max: 2, message: '频率惩罚必须在-2到2之间' }]}
            >
              <InputNumber min={-2} max={2} step={0.1} style={{ width: '100%' }}  placeholder="频率惩罚必须在-2到2之间" />
            </Form.Item>

            <Form.Item
              name="presencePenalty"
              label="存在惩罚"
              rules={[{ type: 'number', min: -2, max: 2, message: '存在惩罚必须在-2到2之间' }]}
            >
              <InputNumber min={-2} max={2} step={0.1} style={{ width: '100%' }}  placeholder="存在惩罚必须在-2到2之间" />
            </Form.Item>

            <Form.Item
              name="version"
              label="模型版本"
              rules={[
                { pattern: /^[0-9]+\.[0-9]+\.[0-9]+$/, message: '版本号格式不正确，如：1.0.0' }
              ]}
            >
              <Input placeholder="请输入模型版本,如：1.0.0" />
            </Form.Item>
          </Panel>
        </Collapse>
      )}

      {/* 高级设置卡片 - 使用 Collapse 实现折叠 */}
      <Collapse
        activeKey={activeAdvancedKeys}
        onChange={setActiveAdvancedKeys}
        expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
        style={{ marginBottom: 16 }}
      >
        <Panel header="高级设置" key="advanced">
          <Form.Item
            name="isEnabled"
            label="是否启用"
            valuePropName="checked"
            initialValue={true}
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="rateLimit"
            label="速率限制（次/分钟）"
            rules={[{ type: 'number', min: 1, message: '速率限制必须大于0' }]}
          >
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="timeout"
            label="超时时间（毫秒）"
            rules={[{ type: 'number', min: 1000, message: '超时时间必须大于1000毫秒' }]}
          >
            <InputNumber min={1000} step={1000} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="retryTimes"
            label="重试次数"
            rules={[{ type: 'number', min: 0, max: 5, message: '重试次数必须在0到5之间' }]}
          >
            <InputNumber min={0} max={5} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="retryInterval"
            label="重试间隔（毫秒）"
            rules={[{ type: 'number', min: 1000, message: '重试间隔必须大于1000毫秒' }]}
          >
            <InputNumber min={1000} step={1000} style={{ width: '100%' }} />
          </Form.Item>
        </Panel>
      </Collapse>

      {/* 表单按钮 */}
      <Form.Item>
        <Space>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
          <Button onClick={onCancel}>
            取消
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default ModelForm;